package com.sunday.volunteer.ui.mine;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunday.common.imageselector.MultiImageSelectorActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ImageUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.pickerview.TimePickerView;
import com.sunday.member.base.BaseActivity;
import com.sunday.member.utils.UploadUtils;
import com.sunday.volunteer.BaseApp;
import com.sunday.volunteer.R;
import com.sunday.volunteer.entity.Images;
import com.sunday.volunteer.entity.Member;
import com.sunday.volunteer.http.HttpClient;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/*
* 发布志愿活动
* */
public class PublishActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.title_text)
    TextView titleView;
    @Bind(R.id.commentPic)
    GridView imgs;
    @Bind(R.id.btn_submit)
    Button submit;
    @Bind(R.id.et_startDate)
    TextView etStartDate;
    @Bind(R.id.et_endDate)
    TextView etEndDate;
    @Bind(R.id.checkbox)
    TextView checkbox;
    @Bind(R.id.et_name)
    EditText etName;
    @Bind(R.id.et_address)
    EditText etAddress;
    @Bind(R.id.et_num)
    EditText etNum;
    @Bind(R.id.et_detial)
    EditText etDetial;

    private Member member;

    //本地图片
    private List<String> imglist = new ArrayList<>();
    private GridAdapter gridAdapter;

    private String mainImg,name, startTime, endTime, address,teamNums,detials;
    private int limitNumber, isPrivate;
    private ArrayList<String> rollImages = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish);
        ButterKnife.bind(this);
        titleView.setText("发布志愿活动");
        member = BaseApp.getInstance().getMember();
        gridAdapter = new GridAdapter();
        imgs.setAdapter(gridAdapter);
        gridAdapter.setOnClickListener(this);
        submit.setOnClickListener(this);
        checkbox.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img1:
                int position = (int) v.getTag(R.id.position);
                if (imglist.size() == position) {
                    toImage();
                }
                break;
            case R.id.img11:
                int position1 = (int) v.getTag(R.id.position);
                imglist.remove(position1);
                gridAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_submit:
                name = etName.getText().toString().trim();
                address = etAddress.getText().toString().trim();
                teamNums = etNum.getText().toString().trim();
                detials = etDetial.getText().toString().trim();
                if (TextUtils.isEmpty(name)){
                    ToastUtils.showToast(mContext,"活动名称不能为空");
                    return;
                }else if (TextUtils.isEmpty(address)){
                    ToastUtils.showToast(mContext,"活动地点不能为空");
                    return;
                }else if (TextUtils.isEmpty(teamNums)){
                    ToastUtils.showToast(mContext,"活动人数不能为空");
                    return;
                }else if (TextUtils.isEmpty(startTime)){
                    ToastUtils.showToast(mContext,"请选择开始时间");
                    return;
                }else if (TextUtils.isEmpty(endTime)){
                    ToastUtils.showToast(mContext,"请选择结束时间");
                    return;
                }else if (!compareDate(end,start)){
                    ToastUtils.showToast(mContext,"活动时间区间不正确");
                    return;
                }else if (imglist.size()==0){
                    ToastUtils.showToast(mContext,"请选择活动主图");
                    return;
                }
                limitNumber = Integer.parseInt(teamNums);
                if (limitNumber<=0){
                    ToastUtils.showToast(mContext,"活动人数不能为0");
                    return;
                }
                uploadImg(UploadUtils.getRequestBody(imglist));
                break;
            case R.id.checkbox:
                checkbox.setSelected(!checkbox.isSelected());
                break;
        }
    }

    //提交活动
    private void crateAction(){
        isPrivate = checkbox.isSelected()?1:0;
        showLoadingDialog(0);
        Call<ResultDO> call = HttpClient.getHttpAdapter()
                .createActivity(member.getId(),name,limitNumber,startTime,endTime,
                        address,mainImg, StringUtils.listToString(rollImages),isPrivate ,detials);

        Log.d("aa" , name + limitNumber+startTime +end +address +mainImg + StringUtils.listToString(rollImages) +isPrivate +detials );

        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (response.body() == null||isFinish){
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "发布成功");
                    finish();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, "网络错误");
            }
        });
    }

    //上传图片
    private void uploadImg(final RequestBody requestBody){
        showLoadingDialog(0);
        Call<ResultDO<List<Images>>> call
                = HttpClient.getHttpAdapter().uploadMultiFile(requestBody);
        call.enqueue(new Callback<ResultDO<List<Images>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<Images>>> call, Response<ResultDO<List<Images>>> response) {
                if (response.body()==null || isFinish){
                    return;
                }
                if (response.body()!=null && response.body().getCode()==0){
                    ToastUtils.showToast(mContext,"上传成功");
                    List<Images> backList = response.body().getResult();
                    rollImages.clear();
                    for (int i = 0;i<backList.size();i++){
                        rollImages.add(backList.get(i).getHalfPath());
                    }
                    mainImg = backList.get(0).getHalfPath();
                    crateAction();
                }else{
                    ToastUtils.showToast(mContext,response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<Images>>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext,"网络错误");
            }
        });
    }


    public void toImage() {
        intent = new Intent(mContext, MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        startActivityForResult(intent, 1111);
    }

    private TimePickerView timePickerView;
    private boolean isStart;//是否选择开始时间
    private Date start, end;

    @OnClick({R.id.et_startDate, R.id.et_endDate})
    public void selectTime(View view) {
        switch (view.getId()) {
            case R.id.et_startDate:
                isStart = true;
                break;
            case R.id.et_endDate:
                isStart = false;
                break;
        }
        if (timePickerView == null) {
            timePickerView = new TimePickerView(mContext, TimePickerView.Type.ALL);
            timePickerView.setTime(new Date());
            timePickerView.setCyclic(false);
            timePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (isStart) {
                        startTime = sdf.format(date);
                        etStartDate.setText("开始时间：" + startTime);
                        start = date;
                    } else {
                        endTime = sdf.format(date);
                        etEndDate.setText("结束时间：" + endTime);
                        end = date;
                    }
                }
            });
        }
        timePickerView.show();
    }

    private ArrayList<String> mSelectPath = new ArrayList<>();
    private SparseArray<String> stringSparseArray = new SparseArray<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        mSelectPath.clear();
        mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
        String imgs = null;
        if (mSelectPath != null) {
            imgs = ImageUtils.getCompressImagePath(mSelectPath.get(0));
            imglist.add(imgs);
            gridAdapter.notifyDataSetChanged();
            stringSparseArray.put(requestCode, imgs);
        }
    }

    /**
     * 比较两个日期之间的大小
     *
     * @param d1
     * @param d2
     * @return 前者大于后者返回true 反之false
     */
    public boolean compareDate(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(d1);
        c2.setTime(d2);

        int result = c1.compareTo(c2);
        if (result > 0)
            return true;
        else
            return false;
    }

    private class GridAdapter extends BaseAdapter {
        private View.OnClickListener onClickListener;
        private int maxImg = 4;

        @Override
        public int getCount() {
            if (imglist.size() >= maxImg) {
                return maxImg;
            } else {
                return imglist.size() + 1;
            }
        }

        @Override
        public Object getItem(int position) {
            return imglist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHower viewHower;
            if (convertView == null) {
                viewHower = new ViewHower();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_img, null);
                viewHower.imageView = (ImageView) convertView.findViewById(R.id.img1);
                viewHower.image = (ImageView) convertView.findViewById(R.id.img11);
                convertView.setTag(viewHower);
            } else {
                viewHower = (ViewHower) convertView.getTag();
            }

            if (position == imglist.size()) {
                viewHower.imageView.setImageResource(R.mipmap.ic_add);
                viewHower.image.setVisibility(View.GONE);
            } else {
                viewHower.imageView.setImageBitmap(BitmapFactory.decodeFile(imglist.get(position)));
                viewHower.image.setVisibility(View.VISIBLE);
            }
            viewHower.imageView.setOnClickListener(onClickListener);
            viewHower.image.setOnClickListener(onClickListener);
            viewHower.imageView.setTag(R.id.position, position);
            viewHower.image.setTag(R.id.position, position);
            return convertView;
        }

        public void setOnClickListener(View.OnClickListener onClickListener) {
            this.onClickListener = onClickListener;
        }

        class ViewHower {
            ImageView imageView;
            ImageView image;
        }

    }
}
